import React, { useEffect, useState } from "react";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { View, Text, Swiper, SwiperItem, Input, Button, ScrollView } from "@tarojs/components";
import { AtToast, AtList, AtListItem, AtFloatLayout, AtMessage } from 'taro-ui';
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/float-layout.scss";
import "taro-ui/dist/style/components/message.scss";
import { getArticle, isConcerned, concernedOther, disConcernedOther, getAllComments, sendComment, reportArticle } from './api';
import css from "./index.module.less";
import { getPrivateChat } from "../../message/api";
import { sendMessage } from "../../message/chat/api";

export default function Index() {
  const { uuid, liked } = getCurrentInstance().router.params;
  const [articleData, setArticleData] = useState(null);
  const [concerned, setConcerned] = useState(0);
  const [userInfo, setUserInfo] = useState({});
  const [comments, setComments] = useState([]);
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState(""); // 发送的消息
  const [isOpenedOperation, setIsOpenedOperation] = useState(false);
  const [isOpenedMessage, setIsOpenedMessage] = useState(false);
  useEffect(() => {
    getArticle(uuid).then(res => {
      if (res.code === 200) {
        const data = res.data;
        getAllComments(data.article.id).then((res) => {
          if (res.code === 200) {
            setComments(res.data);
          }
        })
        data.liked = liked;
        setArticleData(data);
        Taro.getStorage({
          key: 'userInfo',
          success: function (res) {
            setUserInfo(res.data);
            const authorId = data.article.authorId;
            const userId = res.data.id;
            if (userId === authorId) {
              setConcerned(-1); // 表示为自己写的文章
            } else {
              isConcerned(userId, authorId).then((e) => {
                if (e.code === 200) {
                  if (e.data === true) {
                    setConcerned(1); // 已关注
                  } else {
                    setConcerned(0); // 未关注
                  }
                }
              })
            }
          }
        })
      }
    })
  }, [])

  const onConcerned = () => {
    const userId = userInfo.id;
    const authorId = articleData.article.authorId;
    const data = {
      userId: userId,
      concernedId: authorId,
    }
    concernedOther(data).then((res) => {
      if (res.code === 200) {
        console.log("关注成功");
        setConcerned(1);
      } else {
        console.log("失败");
      }
    })
  }

  const disConcerned = () => {
    const userId = userInfo.id;
    const authorId = articleData.article.authorId;
    disConcernedOther(userId, authorId).then((res) => {
      if (res.code === 200) {
        console.log("取消关注成功");
        setConcerned(0);
      } else {
        console.log("失败");
      }
    })
  }
  const changeValue = (e) => {
    setValue(e.target.value);
  }
  const send = () => {
    console.log("发送消息");
    console.log(comments);
    const data = {
      articleId: articleData.article.id,
      authorId: userInfo.id,
      content: value
    }
    sendComment(data).then((res) => {
      if (res.code === 200) {
        console.log(res.data);
      }
    })
    setComments([...comments, {authorId: userInfo.id, avatar: userInfo.avatar, comment: data, commentedList: [], username: userInfo.username}]);
    setValue("");
  }
  const privateChat = () => {
    setOpen(true);
  }
  const operateComment = () => {
    setIsOpenedOperation(true);
  }
  const closeOperationView = () => {
    setIsOpenedOperation(false);
  }
  const allOperations = [{state: 1, title: "举报"}];
  const selectOperation = (e) => {
    setIsOpenedMessage(true);
  }
  const closeMessageView = () => {
    setIsOpenedMessage(false);
  }
  const allMessages = ["站外导流", "违法违规", "色情低俗", "虚假不适", "不友善、引战", "时政不实消息", "涉及成年人", "诱导点赞关注"];
  const selectMessage = (msg) => {
    const data = {
      articleId: articleData.article.id,
      content: msg,
      read: 0,
      reportId: userInfo.id
    }
    reportArticle(data).then((res) => {
      if (res.code === 200) {
        Taro.atMessage({
          'message': res.data,
          'type': "success",
        })
        setIsOpenedOperation(false);
        setIsOpenedMessage(false);
      } else {
        Taro.atMessage({
          'message': "举报失败",
          'type': "error",
        })
      }
    })
  }
  return (
    <React.Fragment>
      <AtMessage />
      <AtToast isOpened={open} text={"不支持再次评论，请直接私聊用户"}></AtToast>
      <View className={css.app}>
        <ScrollView className={css.scroll}
          scrollY
          scrollWithAnimation
          scrollTop={0}
          lowerThreshold={50}
          upperThreshold={50}
        >
          {articleData == null ? "":<View onLongPress={() => operateComment()}>
            <View className={css.header}>
              <View className={css.author}>{articleData.article.author}</View>
              {concerned === -1? "" : concerned === 0? <View className={css.concerned} onClick={onConcerned}>关注</View>: <View className={css.concerned} onClick={disConcerned}>取消关注</View>}
            </View>
            <Swiper
              className={css.swiper}
              indicatorColor='#999'
              indicatorActiveColor='#333'
              circular
              indicatorDots
              autoplay>
                {articleData.images.map((image) => {
                  return (
                    <SwiperItem key={image.id}>
                        <image className={css.img} src={image.url} mode="hightFix"/>
                    </SwiperItem>
                  )
                })}
            </Swiper>
            <View className={css.title}>
              <Text>{articleData.article.title}</Text>
            </View>
            <View className={css.content}>
              <Text className={css.article}>{articleData.article.content}</Text>
              <View><Text className={css.category}># {articleData.sortTitle}</Text></View>
            </View>
            <View className={css.time}>编辑于: {articleData.article.created}</View>
          </View>}

          <AtFloatLayout isOpened={isOpenedOperation} onClose={closeOperationView}>
            {allOperations.map((res, index) => {
              return (
                <AtListItem key={index} title={res.title} onClick={() => selectOperation(res)} />
              )
            })}
          </AtFloatLayout>

          <AtFloatLayout isOpened={isOpenedMessage} onClose={closeMessageView}>
            {allMessages.map((res, index) => {
              return (
                <AtListItem key={index} title={res} onClick={() => selectMessage(res)} />
              )
            })}
          </AtFloatLayout>
          <View className={css.comment_content}>
            {comments.map((comment) => {
              return (
                <View key={comment.comment.id}>
                  <View className={css.comment}>
                    <image className={css.img} src={comment.avatar} />
                    <View className={css.content} style={{"fontSize": "0.8rem"}}>
                      <View>{comment.username}</View>
                      <View>{comment.comment.content}</View>
                    </View>
                  </View>
                  {comment.commentedList.map((commented) => {
                    return (
                      <View className={css.commented}>
                        <image className={css.img} src={commented.avatar} />
                        <View className={css.content} onClick={() => privateChat()} style={{"fontSize": "0.8rem"}}>
                          <View>{commented.username}</View>
                          <View>{commented.commented.content}</View>
                        </View>
                      </View>
                    )
                  })}
                </View>
              )
            })}
          </View>
        </ScrollView>
        <View className={css.bottom}>
          <View className={css.box}>
            <Input value={value} onInput={changeValue} placeholder="请发表评论" className={css.content} />
            <Button className={css.send} onClick={send}>点击</Button>
          </View>
        </View>
      </View>
    </React.Fragment>
  );
}
